package com.leyou.service;

import com.leyou.common.enums.LyEnum;
import com.leyou.common.exception.LyException;
import com.leyou.mapper.SpecGroupMapper;
import com.leyou.pojo.SpecGroup;
import com.leyou.pojo.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class SpecGroupService {
    /**
     *
     * @param cid
     * @return
     */
    @Autowired
    private SpecGroupMapper specGroupMapper;

    @Autowired SpecParamService specParamService;

    public List<SpecGroup> queryGroupByCid(Long cid) {
        SpecGroup group = new SpecGroup();
        group.setCid(cid);
        List<SpecGroup> list = specGroupMapper.select(group);
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(LyEnum.GROUP_NOT_FOUND);
        }
        return list;
    }

    public List<SpecGroup> queryListByCid(Long cid) {
        SpecGroup group = new SpecGroup();
        group.setCid(cid);
        List<SpecGroup> list = specGroupMapper.select(group);
        List<SpecParam> specParams = specParamService.queryParamByid(cid, null);
        Map<Long,List<SpecParam>> map = new HashMap<>();
        for (SpecParam specParam : specParams) {
            if(!map.containsKey(specParam.getCid())){
                map.put(specParam.getCid(), new ArrayList<>());
            }
            map.get(specParam.getCid()).add(specParam);
        }
        for (SpecGroup specGroup : list) {
            specGroup.setSpecs(map.get(specGroup.getCid()));
        }
        return list;
    }
}
